import 'package:cached_network_image/cached_network_image.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';

import '../common/constants.dart';
import '../common/routes.dart';
import '../common/utils.dart';
import '../model/community_video_model.dart';

class VideoCategoryPage extends StatefulWidget {
  const VideoCategoryPage({super.key});

  @override
  State<VideoCategoryPage> createState() => _VideoCategoryPageState();
}

class _VideoCategoryPageState extends State<VideoCategoryPage> {
  final int _id = Get.arguments['id'] ?? 0;
  final String _headImageUrl = Get.arguments['headImageUrl'];
  final String _name = Get.arguments['name'];

  final ScrollController _scrollController = ScrollController();
  final List<IssueList> _videoList = [];
  bool _isLoadingMore = false;
  bool _isLoadingData = true;
  bool _hasMore = true;

  @override
  void initState() {
    super.initState();

    _scrollController.addListener(() {
      if (_scrollController.position.pixels == _scrollController.position.maxScrollExtent && !_isLoadingMore) {
        _loadMore();
      }
    });

    loadData();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  _loadMore() async {
    setState(() {
      _isLoadingMore = true;
    });
    await loadData();
  }

  loadData() async {
    Dio dio = Dio();
    var params = {
      "id": _id,
      "start": _videoList.length,
      "udid": '3e7ee30c6fc0004a773dc33b0597b5732b145c04',
    };
    final url = "https://baobab.kaiyanapp.com/api/v4/categories/videoList";
    final response = await dio.get(url, queryParameters: params);
    var model = CommunityVideoModel.fromJson(response.data);
    setState(() {
      _isLoadingData = false;
      _isLoadingMore = false;
      if (model.count! > 0) {
        _videoList.addAll(model.itemList ?? []);
      } else {
        _hasMore = false;
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: CustomScrollView(
        controller: _scrollController,
        slivers: [
          SliverAppBar(
            iconTheme: IconThemeData(
              color: Colors.white,
            ),
            systemOverlayStyle: SystemUiOverlayStyle(
              statusBarIconBrightness: Brightness.light,
            ),
            backgroundColor: Constants.themeColor,
            expandedHeight: 200.0,
            pinned: true,
            flexibleSpace: FlexibleSpaceBar(
              centerTitle: true,
              title: Padding(
                padding: EdgeInsets.symmetric(horizontal: 40),
                child: Text(
                  _name,
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: Colors.white, fontSize: 17),
                ),
              ),
              expandedTitleScale: 1,
              background: CachedNetworkImage(
                imageUrl: convertImageUrl(_headImageUrl),
                fit: BoxFit.cover,
                fadeInDuration: const Duration(seconds: 0),
                fadeOutDuration: const Duration(seconds: 0),
                placeholder: (context, url) {
                  return Image.asset(
                    "assets/images/placeholder.png",
                    fit: BoxFit.cover,
                  );
                },
              ),
            ),
          ),
          SliverList(
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                if (index == _videoList.length) {
                  if (_isLoadingMore) {
                    // Show loading indicator
                    return Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Center(child: CircularProgressIndicator()),
                    );
                  } else if (!_hasMore) {
                    // No more data
                    return Padding(
                      padding: const EdgeInsets.all(8.0),
                      child: Center(child: Text('没有更多数据了')),
                    );
                  } else {
                    if (_isLoadingData) {
                      return Center(
                        child: Container(
                          margin: const EdgeInsets.all(8.0),
                          width: 64.0,
                          height: 64.0,
                          child: const CircularProgressIndicator(),
                        ),
                      );
                    }
                    return SizedBox.shrink();
                  }
                }

                final item = _videoList[index];
                return GestureDetector(
                  child: Container(
                    color: Colors.white,
                    margin: EdgeInsets.symmetric(vertical: 5, horizontal: 5),
                    child: Column(
                      children: [
                        Stack(
                          children: [
                            CachedNetworkImage(
                              width: double.infinity,
                              height: 200,
                              fadeInDuration: const Duration(seconds: 0),
                              fadeOutDuration: const Duration(seconds: 0),
                              fit: BoxFit.cover,
                              imageUrl: item.data?.cover?.feed ?? '',
                              placeholder: (context, url) {
                                return Image.asset(
                                  "assets/images/placeholder.png",
                                  fit: BoxFit.cover,
                                );
                              },
                            ),
                            Positioned(
                              left: 0,
                              top: 0,
                              child: Container(
                                decoration: BoxDecoration(
                                  color: Colors.red,
                                  borderRadius: BorderRadius.only(
                                    bottomRight: Radius.circular(16),
                                  ),
                                ),
                                width: 46,
                                height: 22,
                                child: Padding(
                                  padding: EdgeInsets.symmetric(horizontal: 8, vertical: 1),
                                  child: Text(
                                    item.data?.category ?? '',
                                    style: TextStyle(color: Colors.white, fontSize: 13),
                                  ),
                                ),
                              ),
                            )
                          ],
                        ),
                        Row(
                          children: [
                            ClipRRect(
                              borderRadius: BorderRadius.circular(20),
                              child: CachedNetworkImage(
                                fit: BoxFit.cover,
                                fadeInDuration: const Duration(milliseconds: 100),
                                fadeOutDuration: const Duration(seconds: 0),
                                imageUrl: item.data?.author?.icon ?? '',
                                width: 40,
                                height: 40,
                              ),
                            ),
                            Expanded(
                              child: Padding(
                                padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      item.data?.author?.name ?? '',
                                      style: TextStyle(fontSize: 18),
                                    ),
                                    Text(
                                      item.data?.author?.description ?? '',
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                        fontSize: 14,
                                        color: Colors.black.withAlpha(127),
                                      ),
                                    )
                                  ],
                                ),
                              ),
                            ),
                          ],
                        )
                      ],
                    ),
                  ),
                  onTap: () {
                    Get.toNamed(Routes.VIDEO_DETAIL, arguments: {"id": item.data?.id, "playUrl": item.data?.playUrl});
                  },
                );
              },
              childCount: _videoList.length + 1,
            ),
          ),
        ],
      ),
    );
  }
}
